const uniID = require('uni-id-common');
const SECRET_KEY = "mindSora@#";
const EXPIRES_IN = "2h";

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const uniIDIns = uniID.createInstance({ context });

  try {
    // 1. 获取 consultant_schedule 中有排班记录的 user_id（去重）
    const scheduleRes = await db.collection('consultant_schedule')
	  .where({ isShow: true })
      .get();

    const userIdSet = new Set(scheduleRes.data.map(i => i.user));
    const userIds = Array.from(userIdSet);

    if (userIds.length === 0) {
      return {
        code: 0,
        data: [],
        msg: "暂无有排班的咨询师"
      };
    }

    // 2. 查询 consultants 表中匹配的记录
    const consultantRes = await db.collection('consultants')
      .where({ user_id: db.command.in(userIds) })
      .get();

    // 3. 给每位咨询师生成 token 并去除 user_id
    if (consultantRes.data && Array.isArray(consultantRes.data)) {
      const dataWithToken = await Promise.all(consultantRes.data.map(async (item) => {
        if (item.user_id) {
          const { token } = await uniIDIns.createToken({ uid: item.user_id });
          const { user_id, ...rest } = item;
          return { ...rest, uniIdToken: token };
        }
        return item;
      }));

      return {
        code: 0,
        data: dataWithToken
      };
    } else {
      return {
        code: 0,
        data: [],
        msg: "未找到匹配咨询师"
      };
    }
  } catch (error) {
    console.error("获取可用咨询师失败:", error);
    return {
      code: 1,
      msg: "服务器错误",
      error
    };
  }
};